<template lang="pug">
data-page.patient-work-list(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )
  templatePreview(v-model="templatePreviewShow",:selectRows= "selectRows",:action="templatePreviewAction" @handleQuery="handleQuery")
  pacsViewerDialog(v-model="pacsViewerDialogShow",:registrationIds="registrationIds",:deviceId="deviceId",@handleQuery="handleQuery")
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type TableProps,
  useNotify,

} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { type QueryPagination, useApi } from "@scmt/core-api";
import {
  type RegistrationEntity,
  type RegistrationQueryParams,
  RegistrationStateEnum,
  adviceColumns,
  ERegistrationColumnKey,
  registrationStateColorMap,
} from "@scmt/api-pacs-registration";

import templatePreview from "./templatePreview.vue";
import pacsViewerDialog from "./pacs-viewer-dialog.vue";
import { useUser } from "@scmt/common-store";

const user = useUser();
const templatePreviewShow = ref(false);
const pacsViewerDialogShow = ref(false);
const templatePreviewAction = ref("");
const registrationIds = ref("");
const deviceId = ref("");
const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<RegistrationQueryParams>({
  name: "",
  pageNum: 1,
  pageSize: 20,
  registrationState: RegistrationStateEnum.Order + "," + RegistrationStateEnum.ToBeDiagnosed + "," + RegistrationStateEnum.Progress + "," + RegistrationStateEnum.Diagnosed,
});
//定义事件
const emit = defineEmits(["selectRow"]);

const editingObj = ref<null | RegistrationEntity>(null);
//选择的列表项
const selectRows = ref([]);
const params = ref({});
const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const paramsNew = Object.assign({ executionOfficeId: user.currentOfficeId ?? "currentOfficeId" }, queryPramas, q);
    params.value = Object.assign({ executionOfficeId: user.currentOfficeId }, queryPramas, q);
    return $api.pacs.registration.query(paramsNew);
  },
  save: (model: RegistrationEntity) => {
    return $api.pacs.registration.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.pacs.registration.destroy(ids).then(() => {
      $notify.success("删除成功");

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  //患者类型字典
  patientType: () => $api.dict.item.listAsOptions("patient-type"),
  //导出excel
  excelExport: () => {
    const paramsImport = Object.assign({}, queryPramas, params.value);
    return $api.pacs.registration.excelExport(paramsImport);
  },

});

onMounted(() => {
  request("patientType");
  request("tableData");
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [];
  const headerActions: Action[] = [
    {
      label: "报告",
      event: "report",
      type: "primary",
      disabled: selectRows?.value?.length != 1,
    },
    {
      label: "影像",
      event: "image",
      type: "primary",
      //@ts-ignore
      disabled: selectRows?.value?.length != 1 || (selectRows?.value?.length == 1 && (!selectRows?.value[0]?.dicomCount || selectRows?.value[0]?.dicomCount == 0)),
    },
    {
      label: "审核",
      event: "examine",
      type: "primary",
      disabled:
        selectRows?.value?.length != 1 ||
        editingObj?.value?.registrationState != "6",
    },
    {
      label: "打印",
      event: "print",
      type: "primary",
      disabled:
        selectRows?.value?.length != 1 ||
        (editingObj?.value?.registrationState != "7" &&
          editingObj?.value?.registrationState != "8"),
    },
    // { label: "关联检查", event: "", type: "primary", disabled: selectRows?.value?.length != 1 },
    // { label: "追加报告", event: "", type: "primary", disabled: selectRows?.value?.length != 1 },
    { label: "导出列表", event: "export", type: "primary" },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => request("tableData"),
    onAct: onPageActions,
    columns: 4,
    alignAction: "left",
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "selection",
        label: "序号",
        width: "60px",
      },
      adviceColumns[ERegistrationColumnKey.RegistrationStateLable],
      adviceColumns[ERegistrationColumnKey.PatientType],
      adviceColumns[ERegistrationColumnKey.InspectionNumber],
      adviceColumns[ERegistrationColumnKey.AdmissionNumber],
      adviceColumns[ERegistrationColumnKey.Name],
      adviceColumns[ERegistrationColumnKey.Sex],
      adviceColumns[ERegistrationColumnKey.Age],
      adviceColumns[ERegistrationColumnKey.DeviceName],
      adviceColumns[ERegistrationColumnKey.ProjectName],
      adviceColumns[ERegistrationColumnKey.DicomCount],
      adviceColumns[ERegistrationColumnKey.ApplyOfficeName],
      adviceColumns[ERegistrationColumnKey.RegistrationTime],
    ],
    onAct: onPageActions,
    highlightCurrentRow: true,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    onSelectionChange: (row: any) => {
      selectRows.value = row;

    },
    onRowClick: (row: any) => {
      editingObj.value = $api.pacs.registration.$$createEntity(row);
      emit("selectRow", editingObj.value);
    },
    //@ts-ignore
    cellStyle: ({ row, column }) => {
      if (column.property === adviceColumns[ERegistrationColumnKey.RegistrationStateLable].prop) {
        return {
          //@ts-ignore
          backgroundColor: `${registrationStateColorMap[row[column.property]] || ""} !important`,
        }
      }
    },
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.pacs.registration.$$createEntity(model);
      break;
    case "destroy":
      request("destroy", model ? model.id : "");
      break;
    case "image":

      let ids = "";
      selectRows.value.forEach((element) => {
        //@ts-ignore
        if (element && element.id) {
          if (ids) {
            ids += ",";
          }
          //@ts-ignore
          ids += element.id;
          //@ts-ignore
          deviceId.value = element.deviceId;
        }
      });
      pacsViewerDialogShow.value = true;
      registrationIds.value = ids;

      // window.open(
      //   "/#/pacs/workList/pacsViewer/viewer?registrationIds=" + ids,
      //   "_blank"
      // );
      break;
    case "report":
      templatePreviewShow.value = true;
      templatePreviewAction.value = "report";
      break;
    case "examine":
      templatePreviewAction.value = "examine";
      templatePreviewShow.value = true;
      break;
    case "print":
      templatePreviewAction.value = "print";
      templatePreviewShow.value = true;
      break;
    //导出
    case "export":
      request("excelExport");
      break;
  }
};
//查询
const handleQuery = (q: any) => {
  if (q.registrationState && q.registrationState.trim().length == 0) {
    q.registrationState = RegistrationStateEnum.Order + "," + RegistrationStateEnum.ToBeDiagnosed + "," + RegistrationStateEnum.Progress + "," + RegistrationStateEnum.Diagnosed
  }
  return request("tableData", q);
};

defineExpose({
  handleQuery,
});
//监听科室改变
watch(
  () => user.currentOfficeId,
  (item) => {
    if (item) {
      request("tableData", {});
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped>
.patient-work-list {

  //取消
  .registration-state-cancel {
    width: 100%;
    color: rgb(255, 255, 255);
    background: rgb(231, 7, 19);
  }

  //待检查
  .registration-state-inspect {
    width: 100%;
    color: rgb(255, 255, 255);
    background: rgb(230, 162, 60);
  }
}
</style>
